package com.zwcl.upms.wechat.controller;

import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.redis.RedisService;
import com.zwcl.upms.wechat.api.dto.BindPhoneDto;
import com.zwcl.upms.wechat.api.dto.DecodeUserDto;
import com.zwcl.upms.wechat.api.dto.LoginDto;
import com.zwcl.upms.wechat.service.WxLoginAuthService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/wxAuth")
@Api(value = "wxAuth", tags = "微信授权登录")
public class WxAuthController {
    @Autowired
    WxLoginAuthService wxLoginAuthService;

    /**
     * 根据code登录，获取保存openId和sessionkey
     * @param dto
     * @return
     */
    @PostMapping(value="/login")
    public ApiResult wxLogin(HttpServletRequest request, @Validated @RequestBody LoginDto dto){
        return  wxLoginAuthService.wechatLogin(dto.getLoginCode(),dto.getAppCode());
    }

    /**
     * 根据token判断用户是否已经登录过
     * TODO:网关中已经校验了令牌过期，此处相当于做了两次
     * @param token
     * @return
     */
    @GetMapping("/checkLogin")
    public ApiResult checkSession(@RequestParam(value = "token",required = true)String token){
        return  wxLoginAuthService.checkLogin(token);
    }

    /**
     * 解密用户信息
     * @param dto
     * @return
     */
    @PostMapping("/decodeUser")
    public ApiResult decodeUserInfo(HttpServletRequest request, @Validated @RequestBody DecodeUserDto dto){
        return wxLoginAuthService.getDecodeUser(dto.getIv(),dto.getEncryptedData(),dto.getUserToken(),dto.getAppCode());
    }

    /**
     * 绑定微信手机号码
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/decodePhone")
    public ApiResult decodePhone(HttpServletRequest request, @Validated @RequestBody BindPhoneDto dto){
       return wxLoginAuthService.bindPhone(dto);
    }
}
